package com.salon.modules.gen.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.salon.common.http.response.PageResult;
import com.salon.common.utils.Query;
import com.salon.modules.gen.mapper.GeneratorMapper;
import com.salon.modules.gen.utils.GenUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 */
@Service
public class SysGeneratorService {

    @Autowired
    private GeneratorMapper generatorDao;

    public PageResult<Map<String, Object>> queryList(Map<String, Object> params) {
        IPage<Map<String, Object>> pageParams = new Query<Map<String, Object>>().getPage(params);
        IPage<Map<String, Object>> page = generatorDao.queryList(pageParams, params);
        return new PageResult<>(page.getTotal(), page.getCurrent(), page.getSize(), page.getRecords());
    }

    public Map<String, String> queryTable(String tableName) {
        return generatorDao.queryTable(tableName);
    }

    public List<Map<String, String>> queryColumns(String tableName) {
        return generatorDao.queryColumns(tableName);
    }

    public byte[] generatorCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            GenUtils.generatorCode(table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

}
